import type {
  FormFieldConfig,
  Location,
  OnActionClickFn,
  TableColumnConfig,
  Warehouse,
} from './types';

import { z } from 'zod';

import { $t } from '#/locales';

import { getLocationList, getWarehouseList } from './services';
/**
 * 搜索表单配置
 * @returns 搜索表单字段配置数组
 */
export function useGridFormSchema(): FormFieldConfig[] {
  return [
    {
      field: 'product_code',
      component: 'Input',
      label: $t('inventory.inventory.productCode'),
      componentProps: {
        placeholder: $t('inventory.inventory.productCodePlaceholder'),
      },
      colProps: {
        span: 6,
      },
      validate: {
        validator: z
          .string()
          .max(50, $t('common.maxLength', { n: 50 }))
          .optional(),
      },
    },
    {
      field: 'product_name',
      component: 'Input',
      label: $t('inventory.inventory.productName'),
      componentProps: {
        placeholder: $t('inventory.inventory.productNamePlaceholder'),
      },
      colProps: {
        span: 6,
      },
      validate: {
        validator: z
          .string()
          .max(100, $t('common.maxLength', { n: 100 }))
          .optional(),
      },
    },
    {
      field: 'warehouse',
      component: 'ApiSelect',
      label: $t('inventory.inventory.warehouse'),
      componentProps: {
        placeholder: $t('inventory.inventory.warehousePlaceholder'),
        api: getWarehouseList,
        params: { page_size: 999 },
        labelField: 'warehouse_name',
        valueField: 'warehouse_id',
      },
      colProps: {
        span: 6,
      },
      validate: {
        validator: z.string().optional(),
      },
    },
    {
      field: 'location',
      component: 'ApiSelect',
      label: $t('inventory.inventory.location'),
      componentProps: {
        placeholder: $t('inventory.inventory.locationPlaceholder'),
        api: getLocationList,
        params: {
          page_size: 999,
          warehouse_id: ({ formModel }: any) => formModel?.warehouse,
        },
        labelField: 'location_name',
        valueField: 'location_id',
      },
      colProps: {
        span: 6,
      },
      validate: {
        validator: z.string().optional(),
      },
    },
    {
      field: 'status',
      component: 'Select',
      label: $t('inventory.inventory.status'),
      componentProps: {
        placeholder: $t('inventory.inventory.statusPlaceholder'),
        options: [
          { label: $t('inventory.status.normal'), value: 'normal' },
          { label: $t('inventory.status.warning'), value: 'warning' },
          { label: $t('inventory.status.shortage'), value: 'shortage' },
          { label: $t('inventory.status.excess'), value: 'excess' },
        ],
      },
      colProps: {
        span: 6,
      },
      validate: {
        validator: z
          .enum(['normal', 'warning', 'shortage', 'excess'])
          .optional(),
      },
    },
    {
      field: 'lot_number',
      component: 'Input',
      label: $t('inventory.inventory.batchNumber'),
      componentProps: {
        placeholder: $t('inventory.inventory.batchNumberPlaceholder'),
      },
      colProps: {
        span: 6,
      },
      validate: {
        validator: z
          .string()
          .max(50, $t('common.maxLength', { n: 50 }))
          .optional(),
      },
    },
    {
      field: 'expiry_date_range',
      component: 'RangePicker',
      label: $t('inventory.inventory.expiryDateRange'),
      componentProps: {
        format: 'YYYY-MM-DD',
        placeholder: [$t('common.startDate'), $t('common.endDate')],
      },
      colProps: {
        span: 12,
      },
      validate: {
        validator: z
          .tuple([z.date().optional(), z.date().optional()])
          .optional(),
      },
    },
  ];
}

/**
 * 表格列配置
 * @param onActionClick 操作按钮点击回调函数
 * @returns 表格列配置数组
 */
export function useColumns(
  onActionClick?: OnActionClickFn,
): TableColumnConfig[] {
  return [
    {
      type: 'checkbox',
      width: 50,
      field: '_checkbox',
      title: '',
    },
    {
      field: 'product_code',
      title: $t('inventory.inventory.productCode'),
      width: 150,
      sortable: true,
    },
    {
      field: 'product_name',
      title: $t('inventory.inventory.productName'),
      width: 200,
      sortable: true,
    },
    {
      field: 'specification',
      title: $t('inventory.inventory.specification'),
      width: 180,
    },
    {
      field: 'unit',
      title: $t('inventory.inventory.unit'),
      width: 100,
    },
    {
      field: 'quantity',
      title: $t('inventory.inventory.currentQuantity'),
      width: 120,
      align: 'right',
      sortable: true,
    },
    {
      field: 'safety_stock',
      title: $t('inventory.inventory.safetyStock'),
      width: 120,
      align: 'right',
      sortable: true,
    },
    {
      field: 'warehouse_name',
      title: $t('inventory.inventory.warehouse'),
      width: 150,
      formatter: (row: any) => row.warehouse?.warehouse_name || '-',
    },
    {
      field: 'location_name',
      title: $t('inventory.inventory.location'),
      width: 150,
      formatter: (row: any) => row.location?.location_name || '-',
    },
    {
      field: 'unit_cost',
      title: $t('inventory.inventory.costPrice'),
      width: 100,
      align: 'right',
      sortable: true,
      formatter: (row: any) => row.unit_cost?.toFixed(2) || '0.00',
    },
    {
      field: 'inventory_value',
      title: $t('inventory.inventory.inventoryValue'),
      width: 120,
      align: 'right',
      sortable: true,
      formatter: (row: any) => {
        const value = (row.quantity || 0) * (row.unit_cost || 0);
        return value.toFixed(2);
      },
    },
    {
      field: 'status',
      title: $t('inventory.inventory.status'),
      width: 120,
      align: 'center',
      sortable: true,
      formatter: (row: any) => {
        const statusMap: Record<string, { color: string; label: string }> = {
          normal: { label: $t('inventory.status.normal'), color: '#52c41a' },
          warning: { label: $t('inventory.status.warning'), color: '#faad14' },
          shortage: {
            label: $t('inventory.status.shortage'),
            color: '#ff4d4f',
          },
          excess: { label: $t('inventory.status.excess'), color: '#1890ff' },
        };
        const status = row.status || 'normal';
        const statusInfo = statusMap[status] || statusMap.normal;
        return {
          props: {
            type: status === 'shortage' ? 'error' : 'default',
            style: {
              backgroundColor: statusInfo?.color || '#52c41a',
              borderColor: statusInfo?.color || '#52c41a',
              color: '#fff',
            },
          },
          children: statusInfo?.label || $t('inventory.status.normal'),
        };
      },
    },
    {
      field: 'batch_number',
      title: $t('inventory.inventory.batchNumber'),
      width: 150,
    },
    {
      field: 'expiry_date',
      title: $t('inventory.inventory.expiryDate'),
      width: 150,
      sortable: true,
      formatter: (row: any) => {
        if (!row.expiry_date) return '-';
        return new Date(row.expiry_date).toLocaleDateString();
      },
    },
    {
      field: 'creator',
      title: $t('common.db_field.creator'),
      width: 120,
    },
    {
      field: 'modifier',
      title: $t('common.db_field.modifier'),
      width: 120,
    },
    {
      field: 'update_time',
      title: $t('common.db_field.update_time'),
      width: 180,
      sortable: true,
      formatter: (row: any) => {
        if (!row.update_time) return '-';
        return new Date(row.update_time).toLocaleString();
      },
    },
    {
      field: 'create_time',
      title: $t('common.db_field.create_time'),
      width: 180,
      sortable: true,
      formatter: (row: any) => {
        if (!row.create_time) return '-';
        return new Date(row.create_time).toLocaleString();
      },
    },
    {
      field: 'is_deleted',
      title: $t('common.db_field.is_deleted'),
      width: 100,
      align: 'center',
      formatter: (row: any) => {
        return row.is_deleted ? '是' : '否';
      },
    },
    {
      field: 'action',
      title: $t('common.action'),
      fixed: 'right',
      width: 200,
      align: 'center',
      toolbarRender: {
        slots: {
          default: ({ row }: { row: any }) => [
            {
              code: 'detail',
              name: $t('common.detail'),
              icon: 'icon-detail',
              onClick: () => onActionClick?.({ code: 'detail', row }),
            },
            {
              code: 'adjust',
              name: $t('inventory.inventory.adjust'),
              icon: 'icon-edit',
              onClick: () => onActionClick?.({ code: 'adjust', row }),
            },
            {
              code: 'move',
              name: $t('inventory.inventory.move'),
              icon: 'icon-transfer',
              onClick: () => onActionClick?.({ code: 'move', row }),
            },
          ],
        },
      },
    },
  ];
}

/**
 * 库存调整表单配置
 * @returns 调整表单字段配置数组
 */
export function useAdjustFormSchema(): FormFieldConfig[] {
  return [
    {
      field: 'product_code',
      component: 'Input',
      label: $t('inventory.inventory.productCode'),
      componentProps: {
        disabled: true,
      },
      colProps: {
        span: 24,
      },
    },
    {
      field: 'product_name',
      component: 'Input',
      label: $t('inventory.inventory.productName'),
      componentProps: {
        disabled: true,
      },
      colProps: {
        span: 24,
      },
    },
    {
      field: 'current_quantity',
      component: 'InputNumber',
      label: $t('inventory.inventory.currentQuantity'),
      componentProps: {
        disabled: true,
        min: 0,
        precision: 2,
      },
      colProps: {
        span: 24,
      },
    },
    {
      field: 'adjust_type',
      component: 'RadioGroup',
      required: true,
      label: $t('inventory.inventory.adjustType'),
      defaultValue: 'adjust_in',
      componentProps: {
        options: [
          { label: $t('inventory.inventory.adjustIn'), value: 'adjust_in' },
          { label: $t('inventory.inventory.adjustOut'), value: 'adjust_out' },
        ],
      },
      colProps: {
        span: 24,
      },
      validate: {
        validator: z.enum(['adjust_in', 'adjust_out']).default('adjust_in'),
      },
    },
    {
      field: 'adjust_quantity',
      component: 'InputNumber',
      required: true,
      label: $t('inventory.inventory.adjustQuantity'),
      componentProps: {
        min: 0.01,
        step: 0.01,
        precision: 2,
      },
      colProps: {
        span: 24,
      },
      validate: {
        validator: z
          .number()
          .min(0.01, $t('inventory.inventory.adjustQuantityMin')),
      },
    },
    {
      field: 'reason',
      component: 'Textarea',
      required: true,
      label: $t('inventory.inventory.adjustReason'),
      componentProps: {
        rows: 4,
        placeholder: $t('inventory.inventory.adjustReasonPlaceholder'),
      },
      colProps: {
        span: 24,
      },
      validate: {
        validator: z
          .string()
          .min(1, $t('common.required'))
          .max(200, $t('common.maxLength', { n: 200 })),
      },
    },
    {
      field: 'remark',
      component: 'Textarea',
      label: $t('common.remark'),
      componentProps: {
        rows: 2,
        placeholder: $t('common.remarkPlaceholder'),
      },
      colProps: {
        span: 24,
      },
      validate: {
        validator: z
          .string()
          .max(500, $t('common.maxLength', { n: 500 }))
          .optional(),
      },
    },
  ];
}

/**
 * 库存移动表单配置
 * @param warehouseList 仓库列表引用
 * @param locationList 库位列表引用
 * @returns 移动表单字段配置数组
 */
export function useMoveFormSchema(
  warehouseList: any,
  locationList: any,
): FormFieldConfig[] {
  return [
    {
      field: 'product_code',
      component: 'Input',
      label: $t('inventory.inventory.productCode'),
      componentProps: {
        disabled: true,
      },
      colProps: {
        span: 24,
      },
    },
    {
      field: 'product_name',
      component: 'Input',
      label: $t('inventory.inventory.productName'),
      componentProps: {
        disabled: true,
      },
      colProps: {
        span: 24,
      },
    },
    {
      field: 'from_warehouse',
      component: 'Select',
      label: $t('inventory.moveModal.fromWarehouse'),
      componentProps: {
        placeholder: $t('inventory.moveModal.fromWarehousePlaceholder'),
        options:
          warehouseList.value?.map((item: Warehouse) => ({
            label: item.warehouse_name,
            value: item.warehouse_id,
          })) || [],
        disabled: true,
      },
      colProps: {
        span: 24,
      },
    },
    {
      field: 'from_location',
      component: 'Select',
      label: $t('inventory.moveModal.fromLocation'),
      componentProps: {
        placeholder: $t('inventory.moveModal.fromLocationPlaceholder'),
        options:
          locationList.value?.map((item: Location) => ({
            label: item.location_name,
            value: item.location_id,
          })) || [],
        disabled: true,
      },
      colProps: {
        span: 24,
      },
    },
    {
      field: 'current_quantity',
      component: 'InputNumber',
      label: $t('inventory.inventory.currentQuantity'),
      componentProps: {
        disabled: true,
        min: 0,
        precision: 2,
      },
      colProps: {
        span: 24,
      },
    },
    {
      field: 'to_warehouse',
      component: 'ApiSelect',
      required: true,
      label: $t('inventory.moveModal.toWarehouse'),
      componentProps: {
        placeholder: $t('inventory.moveModal.toWarehousePlaceholder'),
        api: getWarehouseList,
        params: { page_size: 999 },
        labelField: 'warehouse_name',
        valueField: 'warehouse_id',
      },
      colProps: {
        span: 24,
      },
      validate: {
        validator: z.string().min(1, $t('common.required')),
      },
    },
    {
      field: 'to_location',
      component: 'ApiSelect',
      required: true,
      label: $t('inventory.moveModal.toLocation'),
      componentProps: {
        placeholder: $t('inventory.moveModal.toLocationPlaceholder'),
        api: getLocationList,
        params: {
          page_size: 999,
          warehouse_id: ({ formModel }: any) => formModel?.to_warehouse,
        },
        labelField: 'location_name',
        valueField: 'location_id',
        showSearch: true,
      },
      colProps: {
        span: 24,
      },
      validate: {
        validator: z.string().min(1, $t('common.required')),
      },
    },
    {
      field: 'move_quantity',
      component: 'InputNumber',
      required: true,
      label: $t('inventory.moveModal.quantity'),
      componentProps: {
        min: 0.01,
        step: 0.01,
        precision: 2,
      },
      colProps: {
        span: 24,
      },
      validate: {
        validator: z.number().min(0.01, $t('inventory.moveModal.quantityMin')),
      },
    },
    {
      field: 'reason',
      component: 'Textarea',
      required: true,
      label: $t('inventory.moveModal.reason'),
      componentProps: {
        rows: 4,
        placeholder: $t('inventory.moveModal.reasonPlaceholder'),
      },
      colProps: {
        span: 24,
      },
      validate: {
        validator: z
          .string()
          .min(1, $t('common.required'))
          .max(200, $t('common.maxLength', { n: 200 })),
      },
    },
    {
      field: 'remark',
      component: 'Textarea',
      label: $t('common.remark'),
      componentProps: {
        rows: 2,
        placeholder: $t('common.remarkPlaceholder'),
      },
      colProps: {
        span: 24,
      },
      validate: {
        validator: z
          .string()
          .max(500, $t('common.maxLength', { n: 500 }))
          .optional(),
      },
    },
  ];
}

/**
 * 库存交易记录表格列配置
 * @returns 库存交易记录表格列配置数组
 */
export function useMovementColumns(): TableColumnConfig[] {
  return [
    {
      field: 'transaction_id',
      title: $t('common.id'),
      width: 80,
      align: 'center',
    },
    {
      field: 'product_code',
      title: $t('inventory.inventory.productCode'),
      width: 150,
      sortable: true,
    },
    {
      field: 'product_name',
      title: $t('inventory.inventory.productName'),
      width: 200,
      sortable: true,
    },
    {
      field: 'transaction_type',
      title: $t('inventory.inventory.movementType'),
      width: 120,
      sortable: true,
      formatter: (row: any) => {
        const typeMap: Record<string, string> = {
          stock_in: $t('inventory.movement.in'),
          stock_out: $t('inventory.movement.out'),
          stock_adjust: $t('inventory.movement.adjust'),
          stock_move: $t('inventory.movement.transfer'),
          stock_check: '盘点',
        };
        return typeMap[row.transaction_type] || '-';
      },
    },
    {
      field: 'quantity',
      title: $t('inventory.inventory.quantity'),
      width: 100,
      align: 'right',
      sortable: true,
      formatter: (_row: any, _column: any, cellValue: any) => {
        const num = parseFloat(cellValue || '0');
        return num > 0 ? `+${num}` : num;
      },
    },
    {
      field: 'source_warehouse',
      title: $t('inventory.movement.sourceWarehouse'),
      width: 150,
      formatter: (row: any) => row.source_warehouse?.warehouse_name || '-',
    },
    {
      field: 'source_location',
      title: $t('inventory.movement.sourceLocation'),
      width: 150,
      formatter: (row: any) => row.source_location?.location_name || '-',
    },
    {
      field: 'target_warehouse',
      title: $t('inventory.movement.targetWarehouse'),
      width: 150,
      formatter: (row: any) => row.target_warehouse?.warehouse_name || '-',
    },
    {
      field: 'target_location',
      title: $t('inventory.movement.targetLocation'),
      width: 150,
      formatter: (row: any) => row.target_location?.location_name || '-',
    },
    {
      field: 'reason',
      title: $t('inventory.movement.reason'),
      width: 200,
    },
    {
      field: 'creator',
      title: $t('common.operator'),
      width: 100,
      align: 'center',
    },
    {
      field: 'create_time',
      title: $t('inventory.movement.createdAt'),
      width: 180,
      sortable: true,
      formatter: (row: any) => {
        if (!row.create_time) return '-';
        return new Date(row.create_time).toLocaleString();
      },
    },
  ];
}

/**
 * 搜索表单配置（兼容旧版）
 * @returns 搜索表单字段配置数组
 */
export function useSearchSchema(): FormFieldConfig[] {
  return useGridFormSchema();
}
